using System;
using System.Reflection;
using UnityEngine;
using UnityEditor;
using AK.Wwise.TreeView;

namespace AudioStudio.Editor
{
	[CustomPropertyDrawer(typeof(AudioEventPC))]
	public class AudioEventPCDrawer : AudioBaseTypeDrawer
    {
        public override void SetupSerializedProperties(SerializedProperty property)
        {
            m_objectType = AkWwiseProjectData.WwiseObjectType.EVENT;
            m_typeName = "Event";            
        }

        protected override void OnPickerChanged(SerializedProperty property, TreeViewItem treeItem)
        {
            Guid guid = Guid.Empty;
            if (treeItem != null)
            {
                guid = new Guid((treeItem.DataContext as AkWwiseTreeView.AkTreeInfo).Guid);
            }
            var guidProperty = property.FindPropertyRelative("valueGuid.Array");
            AudioUtility.SetByteArrayProperty(guidProperty, guid.ToByteArray());
            
            var e = AkWwiseProjectData.Instance.FindEvent(guid);

            if (e != null)
            {
                if (e.Name.EndsWith(AudioManager.PlayerCtrlSuffix))
                {
                    property.FindPropertyRelative("ID_PC").intValue = e.ID;

                    string withoutpc = e.Name.Substring(0, e.Name.Length - AudioManager.PlayerCtrlSuffix.Length);
                    var epc = AkWwiseProjectData.Instance.FindEvent(withoutpc);
                    if (epc != null)
                    {
                        property.FindPropertyRelative("ID").intValue = epc.ID;
                        property.FindPropertyRelative("name").stringValue = epc.Name;
                    }
                }
                else
                {
                    property.FindPropertyRelative("ID").intValue = e.ID;
                    property.FindPropertyRelative("name").stringValue = e.Name;

                    var epc = AkWwiseProjectData.Instance.FindEvent(e.Name + AudioManager.PlayerCtrlSuffix);
                    if (epc != null)
                    {
                        property.FindPropertyRelative("ID_PC").intValue = epc.ID;
                    }
                    else
                    {
                        property.FindPropertyRelative("ID_PC").intValue = 0;
                    }
                }
            }
            else
            {
                property.FindPropertyRelative("ID").intValue = 0;
                property.FindPropertyRelative("name").stringValue = string.Empty;
            }
            property.serializedObject.ApplyModifiedProperties();
        }
    }
}

